package com.adtech.farmProducts.activities.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.widgets.load.LoadFactory;
import com.adtech.common.widgets.load.core.LoadManager;
import com.adtech.common.widgets.load.view.AbsView;
import com.adtech.common.widgets.recycler.RecyclerViewAdapter;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.adapter.CommodityListAdapter;
import com.adtech.farmProducts.base.BaseActivity;
import com.adtech.farmProducts.base.BaseNfcActivity;
import com.adtech.farmProducts.model.CommodityInfo;
import com.adtech.farmProducts.model.FUserInfo;
import com.adtech.farmProducts.widget.EmptyView;
import com.adtech.farmProducts.widget.ErrorView;
import com.adtech.farmProducts.widget.LoadingView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Time:2020/6/20
 * Created by xiaocz
 * Describe 商品信息管理
 */
public class CommodityManagementListActivity extends BaseNfcActivity {

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.btn_right)
    TextView btn_right;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    /**
     * DATA
     */
    private LoadManager mLoadManager;
    private CommodityListAdapter commodityListAdapter;
    private int position;

    public static void show(Context context,int position) {
        Intent intent = new Intent(context, CommodityManagementListActivity.class);
        intent.putExtra("position",position);
        context.startActivity(intent);
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        if(bundle!=null){
            position=bundle.getInt("position");
        }
        return super.initArgs(bundle);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_list_commodity_management;
    }


    @Override
    protected void initWidgets() {
        super.initWidgets();
        title.setText("我的商品信息");
        btn_right.setText("新增商品");
        mLoadManager = LoadFactory.getInstance().register(mRecyclerView, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManager.showStateView(LoadingView.class);
                commodityList();
            }
        });
        setRefresh();
    }
    private void setRefresh() {
        // 下拉刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh();
                page = 1;
                commodityList();
            }
        });
        //加载更多
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore();
                page++;
                commodityList();
            }
        });
    }

    private int page = 1;

    @Override
    protected void initData() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        commodityListAdapter = new CommodityListAdapter(new RecyclerViewAdapter.AdapterListenerImpl<CommodityInfo>() {
            @Override
            public void onItemClick(RecyclerViewAdapter.ViewHolder<CommodityInfo> holder, CommodityInfo data) {
                super.onItemClick(holder, data);
                if(position==0){
                    Intent intent=new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("CommodityInfo",data);
                    intent.putExtras(bundle);
                    setResult(200,intent);
                    finish();
                }else {
//                    InfoActivity.show(mContext,data);
                }
            }
        });
        mRecyclerView.setAdapter(commodityListAdapter);
        commodityList();
        super.initData();
    }

    @OnClick({R.id.btn_right})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btn_right:
                Intent intent=new Intent();
                intent.setClass(mContext,AddCommodityActivity.class);
                startActivityForResult(intent,200);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode==200 && resultCode==200){
            commodityList();//刷新
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 商品列表查询
     */
    private void commodityList() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        HashMap<String, String> data = new HashMap<>();
        data.put("productName", "");
        data.put("companyId",new Gson().fromJson(AccountManagers.getAccount(), FUserInfo.class).getInfo().getCompanyId());
        asyncHttpPostFormData.addFormData("data", data);
        asyncHttpPostFormData.addFormData("pageIndex", page);
        asyncHttpPostFormData.addFormData("PageSize", Common.Constant.pageSize);
        okHttpClient.posts(Common.Constant.API_IP + "product/query", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                if (page == 1) {
                    mLoadManager.showStateView(ErrorView.class);
                }
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<List<CommodityInfo>>>() {
                }.getType();
                RspModel<List<CommodityInfo>> rspModel = getAnalysisBase(mLoadManager, response, type, "商品列表查询");
                if (rspModel == null) {
                    if (page == 1) {
                        mLoadManager.showStateView(EmptyView.class);
                    }
                    return;
                }
                if (rspModel.getCode() == 1) {
                    if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                        if (page == 1) {
                            commodityListAdapter.replace(rspModel.getData());
                        } else {
                            commodityListAdapter.add(rspModel.getData());
                        }
                    } else {
                        if (page == 1) {
                            mLoadManager.showStateView(EmptyView.class);
                        } else {
                            App.getInstance().showMessage("已到底啦！");
                        }
                    }
                } else {

                    if (page == 1) {
                        mLoadManager.showStateView(ErrorView.class);
                    }
                }
            }
        });
    }
}
